<template>
<el-row>
<recordForm class="fields-panel" @handleDynamicForm="handleDynamicListRules" :isShowRule="isShowRule" :isOnlyShow="isOnlyShow" :modelId="modelId" :orderId="orderId" :fieldList="fieldList1" :range="range" @change="change" :form="form" :fieldsMap="fieldsMap" ref="formRef"></recordForm>
</el-row>
</template>
<script lang="ts">
import { Component, Vue, Ref, Prop, Provide, Watch } from 'vue-property-decorator'
import recordForm from './FormTs'
import { commonAction, handleData, formRollToFirstError, deepClone } from '@/utils/common'
import { busConfigStore } from '@/afterSales/views/config/serviceConfig/store/busConfigStore';
import { state, mutations } from '@/afterSales/views/spare/store/spareData'
import { CommonModule } from '@/store/modules/common'
import { conditonFn, conditonJudgment } from '../utils/condition'
import { emptyField } from '@/afterSales/utils/valueConfig'
@Component({
  name: 'businessDetail',
  components: {
    recordForm
  }
})
export default class BusinessDetail extends Vue {
  @Prop({ default: [] }) public fieldList!: any[]
  @Prop({ default: [] }) public dynamicFormList!: any[]
  @Prop({ default: false }) public isOnlyShow!: boolean
  @Prop({ default: '' }) public modelId!: string
  @Prop({ default: '' }) public orderId!: string
  @Prop(Object) public form!: object
  @Prop({ default: true }) public isShowRule!: boolean
  public validateForm (formRef?: any, scrollRef?: HTMLDivElement) {
    formRef = formRef || (this.$refs.formRef as any);
    const pass = formRef.validate();
    return pass;
  }

  // private get newForm () {
  //   return this.form
  // }

  @Watch('dynamicFormList', { immediate: true })
  private dynamicFormListChange (val: any) {
    this.handleDynamicListRules('')
  }

  private handleDynamicListRules (key: string) {
    if (this.dynamicFormList.length) {
      for (let i = 0; i < this.dynamicFormList.length; i++) { // 循环动态表单规则
        const { type, updateField } = this.dynamicFormList[i]
        if (type === 1 || (type === 2 && updateField.businessId === key)) {
          if (conditonJudgment(this.dynamicFormList[i]?.filters || [], this.form)) {
            this.handleActions(this.dynamicFormList[i], this.form, true)
          } else {
            if (type === 1) {
              this.handleActions(this.dynamicFormList[i], this.form, false)
            }
          }
        }
      }
    }
  }

  private handleActions (list: any, form: any, isConditonPass: boolean) {
    const formActionList = list.formActionList || []
    for (let k = 0; k < formActionList.length; k++) {
      switch (formActionList[k].actionStatus) {
        case 1: // 显示字段
          this.handleFieldList(formActionList[k] || [], 'hide', !isConditonPass)
          break;
        case 2: // 隐藏字段
          this.handleFieldList(formActionList[k] || [], 'hide', isConditonPass)
          break;
        case 3: // 设置字段值
          this.handleFieldList(formActionList[k] || [], 'set', form)
          break;
        case 4: // 设置为必填
          this.handleFieldList(formActionList[k] || [], 'require', isConditonPass)
          break;
        case 5: // 设置为只读
          this.handleFieldList(formActionList[k] || [], 'disabled', isConditonPass)
          break;
        case 6: // 设置为非必填
          this.handleFieldList(formActionList[k] || [], 'require', !isConditonPass)
          break;
        case 7: // 清空
          this.handleFieldList(formActionList[k] || [], 'clear', form)
          break;
      }
    }
  }

  private handleFieldList (row: any, type: string, data: any) {
    for (let i = 0; i < row.fieldList.length; i++) {
      if (type === 'clear') {
        data[row.fieldList[i].businessId] = emptyField(row.fieldList[i])
      } else if (type === 'set') {
        data[row.fieldList[i].businessId] = row.targetValue
      } else {
        this.fieldMap[row.fieldList[i].businessId][type] = data
      }
    }
  }

  private get fieldMap () {
    const obj = {}
    this.fieldList.map(item => {
      obj[item.businessId] = item
    })
    return obj
  }

  private get fieldList1 () {
    return this.fieldList.map(item => {
      return { ...this.fieldMap[item.businessId], isHidden: false };
    })
  }

  private change () {
    // (this.$refs.form as any).validate();
  }

  public clearValidate () {
    (this.$refs as any).formRef.clearValidate();
  }

  public get fieldsMap () {
    const obj = {};
    this.fieldList.forEach((item: any) => {
      obj[item.businessId] = item;
    });
    return obj;
  }

  private get range () {
    const agents = CommonModule.publicCache.userList
    const range = {
      dept: {},
      roles: {},
      queue: {}
    }
    agents.forEach((item: any) => {
      if (item?.departmentConfig?.departmentIdList?.length) {
        item.departmentConfig.departmentIdList.map(item1 => {
          range.dept[item1] = (range.dept[item1] || []).concat([item._id])
        })
      }
      if (item?.queueList.length) {
        item.queueList.map(item1 => {
          range.queue[item1] = (range.dept[item1] || []).concat([item._id])
        })
      }
    })
    return range
  }

  private getAllHouseOptions () { // 获取仓库数据（包含删除）
    commonAction({
      url: '/server-work/action/wareHouse/query',
      method: 'post',
      data: { isIncludeDel: true }
    }).then(res => {
      if (res.success) {
        mutations.setStateData('obj', 'allHouseObj', res.data.wareHouseItemList)
      }
    })
  }

  private getAllSpare () { // 获取备件品类（包含删除）
    commonAction({
      url: '/server-work/action/spare/query',
      method: 'post',
      data: { isIncludeDel: true }
    }).then(res => {
      if (res.success) {
        mutations.setStateData('obj', 'allCommodityCodeObj', res.data.spareItemList)
      }
    })
  }

  private getAllTypeOptions () { // 获取全部类型数据（包含删除）
    commonAction({
      url: '/server-work/action/spareConfig/listAll',
      method: 'get'
    }).then(res => {
      if (res.success) {
        mutations.setStateData('obj', 'allSpareTypeObj', this.formateSpareType([], res.data.spareTypeList))
        mutations.setStateData('obj', 'allSpareOutStockTypeObj', res.data.spareOutStockTypeList)
        mutations.setStateData('obj', 'allSpareInStockTypeObj', res.data.spareInStockTypeList)
        mutations.setStateData('obj', 'allUnitObj', res.data.unitConfig)
      }
    })
  }

  private formateSpareType (result: any[], val: any[]) {
    val.forEach(item => {
      result.push(item)
      if (Array.isArray(item.children) && item.children.length) {
        this.formateSpareType(result, item.children)
      }
    })
    return result
  }

  private getList () {
    commonAction({ url: '/server-work/action/serviceProject/query', method: 'post', data: {} }).then(res => {
      if (res.success) {
        const allServiceItemObj = {}
        res.data.serviceItemList.forEach(item => {
          allServiceItemObj[item.id] = item
        })
        state.serviceList = res.data?.serviceItemList || []
        state.allServiceObj = allServiceItemObj
      }
    })
  }

  private getCustomerFields () {
    commonAction({ url: '/server-crm/action/config/customer/panel/detail', method: 'get' }).then(res => {
      if (res.success) {
        const cmap = {}
        if (res.data.fields) {
          busConfigStore.customerFields = res.data.fields.map(item => {
            cmap[item.field] = item.name
            return {
              label: item.name,
              value: item.field
            }
          })
          busConfigStore.customerFieldsMap = cmap
        }
      }
    })
  }

  private beforeMount () {
    console.log('businessDetail')
    if (!busConfigStore.serviceList.length) {
      commonAction({
        url: '/server-work/action/serviceGroup/listAll',
        method: 'post'
      }).then(res => {
        if (res.success) {
          handleData(res.data.serviceGroupList, 'service')
        }
      })
    }
    this.getCustomerFields()
    this.getList()
    this.getAllTypeOptions()
    this.getAllHouseOptions()
    this.getAllSpare()
  }
}
</script>
<style scoped lang="stylus">
.fields-panel {
  margin-left: -10px;
  margin-right: -10px;
  display: flex;
  flex-wrap: wrap;
  position: relative;
  box-sizing: border-box;
  /deep/.el-form-item {
    padding-left: 10px;
    padding-right: 10px;
    float: left;
    box-sizing: border-box;
  }
}
.fields-panel:after, .fields-panel:before {
    display: table;
    content: "";
}
</style>
